package com.lemon.smartsafetynew.ui.activity.electrical;

import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafetynew.entity.common.CommonBo;
import com.lemon.smartsafetynew.entity.electrical.ElectricalKeyVo;
import com.lemon.smartsafetynew.net.services.ElectricalServices;
import com.lemon.smartsafetynew.ui.activity.base.BaseActivity;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafetynew.entity.electrical.ElectricalItemVo;
import com.lemon.smartsafetynew.entity.electrical.ElectricialSensorVo;
import com.lemon.smartsafetynew.entity.monitor.MonitorSensorData;
import com.lemon.smartsafetynew.entity.monitor.MonitorSensorResult;
import com.lemon.smartsafetynew.ui.widget.SortView;
import com.lemon.smartsafetynew.ui.widget.marker.MyMarkerView;
import com.lemon.smartsafetynew.util.common.ColorUtil;
import com.lemon.smartsafetynew.util.common.CommonUtil;
import com.lemon.smartsafetynew.util.constants.KeyConstants;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;

/**
 * 实时监测 -- 电气火灾监测
 * 用电安全图表展示页
 * Created by Andrew on 2018/3/12.
 */

public class ElectricalSafeSensorActivity extends BaseActivity {

    @Bind(R.id.monitor_item_name)
    TextView monitorItemName;
    @Bind(R.id.title_layout)
    LinearLayout titleLayout;
    @Bind(R.id.sensor_name_tv)
    TextView sensorNameTv;
    @Bind(R.id.now_value)
    TextView nowValue;
    @Bind(R.id.now_layout)
    LinearLayout nowLayout;
    @Bind(R.id.max_value)
    TextView maxValue;
    @Bind(R.id.max_layout)
    LinearLayout maxLayout;
    @Bind(R.id.min_value)
    TextView minValue;
    @Bind(R.id.min_layout)
    LinearLayout minLayout;
    @Bind(R.id.avg_value)
    TextView avgValue;
    @Bind(R.id.avg_layout)
    LinearLayout avgLayout;
    @Bind(R.id.normal_value)
    TextView normalValue;
    @Bind(R.id.abnormal_value)
    TextView abnormalValue;
    @Bind(R.id.line_chart)
    LineChart lineChart;
    @Bind(R.id.chart_layout)
    LinearLayout chartLayout;
    @Bind(R.id.sensor_value_sort_tv)
    TextView sensorValueSortTv;
    @Bind(R.id.ball_layout)
    LinearLayout ballLayout;
    //@Bind(R.id.sort_view)
    //MonitorSortView sortView;
    SortView sortView;
    @Bind(R.id.main_title)
    TextView mainTitle;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.ll)
    LinearLayout ll;

    private static ElectricalKeyVo detailItemVo;
    private static ElectricalItemVo itemVo;

    private Timer timer;

    @Override
    protected void getBundleArgs() {

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            detailItemVo = (ElectricalKeyVo) bundle.getSerializable(KeyConstants.KEY_ELECTRICAL_SENSOR_INFO);
            itemVo = (ElectricalItemVo) bundle.getSerializable(KeyConstants.KEY_ELECTRICAL_ITEM);
        } else {
            callFinish();
        }
    }


    @Override
    protected int getContentViewId() {
        return R.layout.activity_monitor_sensor;
    }

    @Override
    protected void initViews() {

        sortView = (SortView) findViewById(R.id.sort_view);

        initToolbar();
        initLabelBar();
        initLineChart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        startGetNetData();
    }

    private void initToolbar() {

        toolbar.setTitle("");
        mainTitle.setText("实时趋势图");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                callFinish();
            }
        });

    }

    private void initLabelBar() {

        ll.setVisibility(View.GONE);
        monitorItemName.setText(CommonUtil.avoidNullString(itemVo.getArea()) + " "
                + CommonUtil.avoidNullString(itemVo.getLocation()));
        sensorNameTv.setText(detailItemVo.getDesc() + "  实时趋势图");
        sensorValueSortTv.setText(detailItemVo.getDesc() + "  出现次数前5");
    }

    private void initLineChartLabel(MonitorSensorResult sensorResult) {

        if (sensorResult.getSenseDatalist() == null && sensorResult.getSenseDatalist().size() == 0) {
            return;
        }

        int size = sensorResult.getSenseDatalist().size();

        nowValue.setText(CommonUtil.formatData(sensorResult.getSenseDatalist().get(size - 1).getValue()));
        maxValue.setText(CommonUtil.formatData(sensorResult.getMax()));
        minValue.setText(CommonUtil.formatData(sensorResult.getMin()));
        avgValue.setText(CommonUtil.formatData(sensorResult.getAvg()));
    }

    private void initSortView(List<MonitorSensorData> sensorDatas) {


        HashMap<String, Integer> hashMap = new HashMap<String, Integer>();
        for (MonitorSensorData sensorData : sensorDatas) {

            if (!sensorData.isVaild()) continue; //无效的数据不计入统计排序中

            if (hashMap.get(sensorData.getValue()) != null) {
                Integer value = hashMap.get(sensorData.getValue());
                hashMap.put(sensorData.getValue(), value + 1);
            } else {
                hashMap.put(sensorData.getValue(), 1);
            }
        }

        List<Map.Entry<String, Integer>> infoIds =
                new ArrayList<Map.Entry<String, Integer>>(hashMap.entrySet());

        //排序
        Collections.sort(infoIds, new Comparator<Map.Entry<String, Integer>>() {
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return (o2.getValue() - o1.getValue());
                //return (o1.getKey()).toString().compareTo(o2.getKey());
            }
        });

        List<SortView.CircleDataVo> list = new ArrayList<>();

        for (int i = 0; i < Math.min(infoIds.size(), 5); i++) {
            list.add(new SortView.CircleDataVo(detailItemVo.getDesc(), infoIds.get(i).getKey(), infoIds.get(i).getValue() + "次"));
        }

        sortView.setDataList(list);

    }

    private void callFinish() {
        AppManager.getAppManager().finishActivity(ElectricalSafeSensorActivity.this);
    }

    private void getSensorData() {

        LemonRequestParams params = new LemonRequestParams("");
        params.put("deviceId", itemVo.getDeviceId());
        params.put("param", detailItemVo.getCode());
        Log.i("lala","000"+params.toString());
        ElectricalServices.init().getElectricalChartValue(params);

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMainThread(HttpCallbackEvent event) {

        if (KeyConstants.URL_ELECTRICAL_SENSOR_CHART.equals(event.getTag())) {
            if (HandlerCallback.HttpFlow.START == event.getHttpFlow()) {
                mHUDUtil.showHUD();
            } else if (HandlerCallback.HttpFlow.FINISH == event.getHttpFlow()) {
                mHUDUtil.hidden();

                if (Constants.Result.SUCCESS == event.getEventResult()) {

                    ElectricialSensorVo sensorVo = (ElectricialSensorVo) event.getObj();

                    List<MonitorSensorData> today = new ArrayList<>();
                    List<MonitorSensorData> yesterday = new ArrayList<>();

                    for (int i = 0; i < sensorVo.getToday().getTimeList().size(); i++) {
                        MonitorSensorData data = new MonitorSensorData();
                        data.setTime(sensorVo.getToday().getTimeList().get(i));
                        data.setValue(sensorVo.getToday().getList().get(i));
                        if ("-".equals(sensorVo.getToday().getList().get(i))) {
                            data.setVaild(false);
                        } else {
                            data.setVaild(true);
                        }
                        today.add(data);
                    }

                    for (int i = 0; i < sensorVo.getLastday().getTimeList().size(); i++) {
                        MonitorSensorData data = new MonitorSensorData();
                        data.setTime(sensorVo.getLastday().getTimeList().get(i));
                        data.setValue(sensorVo.getLastday().getList().get(i));
                        if ("-".equals(sensorVo.getLastday().getList().get(i))) {
                            data.setVaild(false);
                        } else {
                            data.setVaild(true);
                        }
                        yesterday.add(data);
                    }

                    //initLineChartLabel(sensorResult);
                    showChartHour(today, yesterday);
                    initSortView(today);

                } else if (Constants.Result.ERROR == event.getEventResult()) {

                    mHUDUtil.showErrorTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            callFinish();
                        }
                    });
                }
            }
        }

    }

    // ======== LineChart ========
    private void initLineChart() {

        lineChart.setDrawGridBackground(false);
        lineChart.setNoDataText("无数据");
        // no description text
        lineChart.getDescription().setEnabled(false);

        // enable touch gestures
        lineChart.setTouchEnabled(true);

        // enable scaling and dragging
        lineChart.setDragEnabled(true);
        lineChart.setScaleEnabled(false);
        lineChart.setScaleXEnabled(true);
        lineChart.setDoubleTapToZoomEnabled(false);
        // mChart.setScaleYEnabled(true);

        // if disabled, scaling can be done on x- and y-axis separately
        lineChart.setPinchZoom(false);

        lineChart.fitScreen();

        // set an alternative background color
        // mChart.setBackgroundColor(Color.GRAY);

        // create a custom MarkerView (extend MarkerView) and specify the layout
        // to use for it
        MyMarkerView mv = new MyMarkerView(ElectricalSafeSensorActivity.this, R.layout.custom_marker_view);
        mv.setChartView(lineChart); // For bounds control
        lineChart.setMarker(mv); // Set the marker to the chart

        YAxis leftAxis = lineChart.getAxisLeft();
        leftAxis.removeAllLimitLines(); // reset all limit lines to avoid overlapping lines
        //leftAxis.setAxisMinimum(0f);  //适配data value
        leftAxis.setDrawZeroLine(false);
        leftAxis.setDrawGridLines(false);

// delete by AndrewYin 这里不需要设置最大最小值了 begin
//        List<Integer> thresholds = StandardUtil.getElectricalThresholds(detailItemVo.getKey());
//        for (int i = 0; i < thresholds.size(); i++) {
//            //Log.e("yxy", "threshold = " + thresholds.get(i));
//            LimitLine ll1 = new LimitLine(thresholds.get(i), String.valueOf(thresholds.get(i)));
//            ll1.setLineWidth(1f);
//            ll1.enableDashedLine(10f, 10f, 0f);
//            if (i == 0) {
//                ll1.setLabelPosition(LimitLine.LimitLabelPosition.RIGHT_BOTTOM);
//                ll1.setLineColor(Color.parseColor("#F6B54E"));
//            } else {
//                ll1.setLabelPosition(LimitLine.LimitLabelPosition.RIGHT_TOP);
//                ll1.setLineColor(Color.parseColor("#EA654F"));
//            }
//            ll1.setTextSize(10f);
//            leftAxis.addLimitLine(ll1);
//        }
//        leftAxis.setDrawLimitLinesBehindData(true);
// delete by AndrewYin 这里不需要设置最大最小值了 end

        // limit lines are drawn behind data (and not on top)
        //leftAxis.setDrawLimitLinesBehindData(true);
        lineChart.getAxisRight().setEnabled(false);

        // add data
        //setLineChartData(24, 1000);

        //lineChart.setVisibleXRangeMaximum(6.2f);
        //lineChart.setVisibleXRangeMinimum(0);
        //lineChart.animateX(500);
        //mChart.invalidate();

        // get the legend (only possible after setting data)
        Legend l = lineChart.getLegend();
        l.setEnabled(false);

        // // dont forget to refresh the drawing
        lineChart.invalidate();

    }

    private void showChartHour(List<MonitorSensorData> today, List<MonitorSensorData> yesterday) {

        // ============ X轴 ============
        List<String> strings = new ArrayList<>();

        if (today.size() == 0) { //今日无数据
            if (yesterday.size() == 0) {
                return; //两日都没数据，直接不画
            } else {
                for (MonitorSensorData sensorData : yesterday) { //当今日的时间轴为空，用昨日的时间轴做x轴
                    strings.add(sensorData.getTime());
                }
            }
        } else {
            if (yesterday.size() == 0) {
                for (MonitorSensorData sensorData : today) {  //当昨日的时间轴为空，用今日的时间轴做x轴
                    strings.add(sensorData.getTime());
                }
            } else {
                for (MonitorSensorData sensorData : yesterday) { //都不为空，用昨日的时间轴做x轴
                    strings.add(sensorData.getTime());
                }
            }
        }

        ArrayList<ILineDataSet> dataSets = new ArrayList<>();

        // ============ 今日 y轴 ============
        if (today.size() != 0) {
            ArrayList<Entry> values1 = new ArrayList<>();
            values1.clear();

            for (int i = 0; i < today.size(); i++) {
                if (!today.get(i).isVaild()) { // 无效数据处理
                    values1.add(new Entry(i, 0, CommonBo.SensorDataStatus.data_error.getValue()));
                } else {
                    values1.add(new Entry(i, Float.valueOf(today.get(i).getValue()), CommonBo.SensorDataStatus.data_normal.getValue()));
                }
            }

            // ----------------------------- Line 1 ----------------------------------

            LineDataSet set1 = new LineDataSet(values1, "DataSet 1");
            set1.setDrawValues(false);

            // set the line to be drawn like this "- - - - - -"
            //set1.enableDashedLine(10f, 5f, 0f);
            //set1.enableDashedHighlightLine(10f, 5f, 0f);

            set1.setCircleColor(Color.parseColor("#448ad0"));
            set1.setColor(Color.parseColor("#448ad0"));

            set1.setLineWidth(2f);
            set1.setCircleRadius(4f);
            set1.setDrawCircleHole(false);
            set1.setValueTextSize(9f);
            set1.setFormLineWidth(1f);
            set1.setFormLineDashEffect(new DashPathEffect(new float[]{10f, 5f}, 0f));
            set1.setFormSize(15.f);
            set1.setHighLightColor(Color.TRANSPARENT);

            set1.setDrawFilled(false);
            set1.setFillColor(Color.parseColor(ColorUtil.lineChartColor));

            dataSets.add(set1); // add the datasets
        }

        // ============ 昨日 y轴 ============
        if (yesterday.size() != 0) {
            ArrayList<Entry> values2 = new ArrayList<>();
            values2.clear();

            for (int i = 0; i < yesterday.size(); i++) {
                if (!yesterday.get(i).isVaild()) { // 无效数据处理
                    values2.add(new Entry(i, 0, CommonBo.SensorDataStatus.data_error.getValue()));
                } else {
                    values2.add(new Entry(i, Float.valueOf(yesterday.get(i).getValue()), CommonBo.SensorDataStatus.data_normal.getValue()));
                }
            }

            // ----------------------------- Line 2 ----------------------------------

            LineDataSet set2 = new LineDataSet(values2, "DataSet 2");
            set2.setDrawValues(false);

            // set the line to be drawn like this "- - - - - -"
            //set1.enableDashedLine(10f, 5f, 0f);
            //set1.enableDashedHighlightLine(10f, 5f, 0f);

            set2.setCircleColor(Color.parseColor("#0adfbc"));
            set2.setColor(Color.parseColor("#0adfbc"));

            set2.setLineWidth(2f);
            set2.setCircleRadius(4f);
            set2.setDrawCircleHole(false);
            set2.setValueTextSize(9f);
            set2.setFormLineWidth(1f);
            set2.setFormLineDashEffect(new DashPathEffect(new float[]{10f, 5f}, 0f));
            set2.setFormSize(15.f);
            set2.setHighLightColor(Color.TRANSPARENT);

            set2.setDrawFilled(false);
            set2.setFillColor(Color.parseColor(ColorUtil.lineChartColor));

            dataSets.add(set2); // add the datasets
        }


        // =========== LineChart具体配置 ==========

        // create a data object with the datasets
        LineData data = new LineData(dataSets);

        // set data
        lineChart.setData(data);

        XAxis xAxis = lineChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setAxisMinimum(0f);
        xAxis.setValueFormatter(new TimeIAxisValueFormatter(strings));
        xAxis.setAvoidFirstLastClipping(true);
        xAxis.setGranularity(1f);

        lineChart.setVisibleXRangeMaximum(4.2f);

        lineChart.moveViewToX(today.size());

        lineChart.invalidate();
    }


    private class TimeIAxisValueFormatter implements IAxisValueFormatter {

        List<String> timeStrList = new ArrayList<>();

        public TimeIAxisValueFormatter(List<String> strings) {
            timeStrList = strings;
        }

        @Override
        public String getFormattedValue(float value, AxisBase axis) {
            //String timeStamp = timeStrList.get((int) value);
            //Date date = CommonUtil.timeStrToDate(timeStamp, TimeFormatConstants.FORMAT_TIME);
            //return CommonUtil.timeToStr(date, TimeFormatConstants.FORMAT_TIME3);

            int val = (int) value;
            if (val >= timeStrList.size() || val < 0) {
                return "";
            } else {
                return timeStrList.get(val);
            }
        }
    }

    /**
     * 按频率获取一次数据
     */
    private final static int TIMES = 1800; //1800s一次

    private void startGetNetData() {

        timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                getSensorData();
            }
        }, 0, 1000 * TIMES);
    }

    /**
     * 清理对象，缓存等
     */
    private void clear() {

        if (timer != null) {
            timer.cancel();
            timer.purge();
            timer = null;
        }
        OkHttpUtils.getInstance().cancelTag(KeyConstants.URL_ELECTRICAL_SENSOR_CHART);
    }

    @Override
    protected void onPause() {
        super.onPause();
        clear();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //sortView.setFlag(false);
        //sortView.setVisibility(View.GONE);
    }
}
